/*
    BibleNotebook - A bible reader software
    Copyright (C) 2014  Williams Fernando Lopez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
 */

/*
 * ConfigPanel.java
 *
 * Created on 2/07/2013, 06:41:33 PM
 */

package com.simplebible.ui.components;

import wl.ui.SimpleColorChooser;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JPopupMenu;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.simplebible.bible.BibleReader;
import wl.util.TextResourcesUtil;
import wl.util.Utils;
import com.simplebible.bible.objects.Bible;
import com.simplebible.objects.Preferences;

/**
 *
 * @author Williams Lopez
 */
public class ConfigPanel extends javax.swing.JPanel {

    private JPopupMenu popup = new JPopupMenu();
    private SimpleColorChooser colorChooser = null;

    private ActionListener marcadoresControlListener;
    private ActionListener referenciasControlListener;
    private ActionListener fontSizeControlListener;
    private ActionListener backgroundColorControlListener;
    private ActionListener fontColorControlListener;
    private ActionListener selectVersionListener;
    private ActionListener diccionarioControlListener;


    /** Creates new form ConfigPanel */
    public ConfigPanel() {
        initComponents();
        try{
            TextResourcesUtil.registrarComponente(this);
        }catch(Exception e){
            Utils.printToLog("Error al colocar el texto", e, Preferences.LOG_LEVEL_ERROR);
        }
        popup.add(this);
        this.spinnerSizeLetra.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                if (fontSizeControlListener != null) {
                    try {
                        spinnerSizeLetra.commitEdit();
                    } catch (Exception ex) {
                    }
                    fontSizeControlListener.actionPerformed(new ActionEvent((Integer) spinnerSizeLetra.getValue(), 0, null));
                }
            }
        });


        Utils.propagateMouseListener(this, new MouseListener() {
            public void mouseClicked(MouseEvent e) {
                if(colorChooser!=null)colorChooser.setVisible(false);
            }
            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }
        });

        refresh();

    }

    public void refresh(){

        setValoresPreferencias();
        //cARGANDO BIBLIAS
        try {
            List<Bible> bibles = BibleReader.getVersions();
            DefaultListModel model = new DefaultListModel();
            for(Bible b : bibles){
                model.addElement(b);
            }
            this.listVersion.setModel(model);
        } catch (Exception e) {
            MainPanel.showNotification("generic_error", e);
            Utils.printToLog("Error al cargar las versiones", e, Preferences.LOG_LEVEL_ERROR);
        }
    }

    public ActionListener getBackgroundColorControlListener() {
        return backgroundColorControlListener;
    }

    public void setBackgroundColorControlListener(ActionListener backgroundColorControlListener) {
        this.backgroundColorControlListener = backgroundColorControlListener;
    }

    public ActionListener getFontColorControlListener() {
        return fontColorControlListener;
    }

    public void setFontColorControlListener(ActionListener fontColorControlListener) {
        this.fontColorControlListener = fontColorControlListener;
    }

    public ActionListener getFontSizeControlListener() {
        return fontSizeControlListener;
    }

    public void setFontSizeControlListener(ActionListener fontSizeControlListener) {
        this.fontSizeControlListener = fontSizeControlListener;
    }

    public ActionListener getMarcadoresControlListener() {
        return marcadoresControlListener;
    }

    public void setMarcadoresControlListener(ActionListener marcadoresControlListener) {
        this.marcadoresControlListener = marcadoresControlListener;
    }

    public ActionListener getReferenciasControlListener() {
        return referenciasControlListener;
    }

    public void setReferenciasControlListener(ActionListener referenciasControlListener) {
        this.referenciasControlListener = referenciasControlListener;
    }

    public ActionListener getDiccionarioControlListener() {
        return diccionarioControlListener;
    }

    public void setDiccionarioControlListener(ActionListener diccionarioControlListener) {
        this.diccionarioControlListener = diccionarioControlListener;
    }

    

    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollPaneVersion = new javax.swing.JScrollPane();
        listVersion = new javax.swing.JList();
        panelOptions = new javax.swing.JPanel();
        chboxReferencias = new javax.swing.JCheckBox();
        labelTamanoLetra = new javax.swing.JLabel();
        chboxMarcadores = new javax.swing.JCheckBox();
        spinnerSizeLetra = new javax.swing.JSpinner();
        buttonValoresPorDefecto = new javax.swing.JButton();
        labelColorLetra = new wl.ui.ButtonLabel();
        labelColorFondo = new wl.ui.ButtonLabel();
        chboxDiccionario = new javax.swing.JCheckBox();

        setBackground(new java.awt.Color(255, 255, 255));

        scrollPaneVersion.setBackground(new java.awt.Color(255, 255, 255));
        scrollPaneVersion.setBorder(javax.swing.BorderFactory.createTitledBorder("Versión"));
        scrollPaneVersion.setForeground(new java.awt.Color(153, 153, 153));

        listVersion.setFont(new java.awt.Font("Tahoma", 0, 14));
        listVersion.setForeground(new java.awt.Color(102, 102, 102));
        listVersion.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Reina Valera 1960", "Nueva Versión Internacional" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        listVersion.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listVersionValueChanged(evt);
            }
        });
        scrollPaneVersion.setViewportView(listVersion);

        panelOptions.setBackground(new java.awt.Color(255, 255, 255));
        panelOptions.setBorder(javax.swing.BorderFactory.createTitledBorder("Otras opciónes"));

        chboxReferencias.setBackground(new java.awt.Color(255, 255, 255));
        chboxReferencias.setText("Mostrar referencias cruzadas");
        chboxReferencias.setToolTipText("Sincroniza las biblias cuando se utilizan en ");
        chboxReferencias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chboxReferenciasActionPerformed(evt);
            }
        });

        labelTamanoLetra.setText("Tamaño de letra:");

        chboxMarcadores.setBackground(new java.awt.Color(255, 255, 255));
        chboxMarcadores.setText("Mostrar marcadores");
        chboxMarcadores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chboxMarcadoresActionPerformed(evt);
            }
        });

        spinnerSizeLetra.setModel(new javax.swing.SpinnerNumberModel(12, 4, 100, 1));
        spinnerSizeLetra.setValue(new Integer(12));
        spinnerSizeLetra.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                spinnerSizeLetraMouseClicked(evt);
            }
        });
        spinnerSizeLetra.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                spinnerSizeLetraKeyReleased(evt);
            }
        });

        buttonValoresPorDefecto.setText("Valores por defecto");
        buttonValoresPorDefecto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonValoresPorDefectoActionPerformed(evt);
            }
        });

        labelColorLetra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/select_by_color.png"))); // NOI18N
        labelColorLetra.setText("Color de letra");
        labelColorLetra.setToolTipText("Seleccionar el color de letra");
        labelColorLetra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                labelColorLetraActionPerformed(evt);
            }
        });

        labelColorFondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simplebible/ui/img/select_by_color.png"))); // NOI18N
        labelColorFondo.setText("Color de fondo");
        labelColorFondo.setToolTipText("Seleccionar el color de fondo");
        labelColorFondo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                labelColorFondoActionPerformed(evt);
            }
        });

        chboxDiccionario.setBackground(new java.awt.Color(255, 255, 255));
        chboxDiccionario.setText("Habilitar diccionario en texto");
        chboxDiccionario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chboxDiccionarioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelOptionsLayout = new javax.swing.GroupLayout(panelOptions);
        panelOptions.setLayout(panelOptionsLayout);
        panelOptionsLayout.setHorizontalGroup(
            panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelOptionsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelOptionsLayout.createSequentialGroup()
                        .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(panelOptionsLayout.createSequentialGroup()
                                .addComponent(labelTamanoLetra)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(spinnerSizeLetra, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(chboxMarcadores)
                            .addComponent(chboxDiccionario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(58, 58, 58))
                    .addGroup(panelOptionsLayout.createSequentialGroup()
                        .addComponent(chboxReferencias, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonValoresPorDefecto)
                    .addComponent(labelColorLetra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelColorFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(92, Short.MAX_VALUE))
        );
        panelOptionsLayout.setVerticalGroup(
            panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelOptionsLayout.createSequentialGroup()
                .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelOptionsLayout.createSequentialGroup()
                        .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(labelColorLetra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(panelOptionsLayout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(chboxMarcadores)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(labelColorFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(panelOptionsLayout.createSequentialGroup()
                                        .addGap(23, 23, 23)
                                        .addComponent(chboxDiccionario)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelOptionsLayout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(panelOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(spinnerSizeLetra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(labelTamanoLetra)))
                            .addComponent(buttonValoresPorDefecto)))
                    .addGroup(panelOptionsLayout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(chboxReferencias)))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(scrollPaneVersion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
                    .addComponent(panelOptions, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollPaneVersion, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelOptions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void chboxMarcadoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chboxMarcadoresActionPerformed
        if(this.marcadoresControlListener!=null){
            evt.setSource(this.chboxMarcadores.isSelected());
            this.marcadoresControlListener.actionPerformed(evt);
        }
    }//GEN-LAST:event_chboxMarcadoresActionPerformed

    private void chboxReferenciasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chboxReferenciasActionPerformed
        if(this.referenciasControlListener!=null){
            evt.setSource(this.chboxReferencias.isSelected());
            this.referenciasControlListener.actionPerformed(evt);
        }
    }//GEN-LAST:event_chboxReferenciasActionPerformed

    private void spinnerSizeLetraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spinnerSizeLetraMouseClicked
        
        if(this.fontSizeControlListener !=null){
            try {
                this.spinnerSizeLetra.commitEdit();
            } catch (Exception e) {
            }
            this.fontSizeControlListener.actionPerformed(new ActionEvent((Integer)this.spinnerSizeLetra.getValue(),evt.getID(),null));
        }
    }//GEN-LAST:event_spinnerSizeLetraMouseClicked

    private void spinnerSizeLetraKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_spinnerSizeLetraKeyReleased
        if(this.fontSizeControlListener !=null){
            try {
                this.spinnerSizeLetra.commitEdit();
            } catch (Exception e) {
            }
            this.fontSizeControlListener.actionPerformed(new ActionEvent((Integer)this.spinnerSizeLetra.getValue(),evt.getID(),null));
        }
    }//GEN-LAST:event_spinnerSizeLetraKeyReleased

    private void buttonValoresPorDefectoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonValoresPorDefectoActionPerformed
        setValoresPorDefecto();
    }//GEN-LAST:event_buttonValoresPorDefectoActionPerformed

    private void listVersionValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listVersionValueChanged

        selectVersion();
        
    }//GEN-LAST:event_listVersionValueChanged

    private void labelColorLetraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelColorLetraActionPerformed
        showSelectForegroundColor();
    }//GEN-LAST:event_labelColorLetraActionPerformed

    private void labelColorFondoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_labelColorFondoActionPerformed
        showSelectBackgrondColor();
    }//GEN-LAST:event_labelColorFondoActionPerformed

    private void chboxDiccionarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chboxDiccionarioActionPerformed
        if(this.diccionarioControlListener!=null){
            evt.setSource(this.chboxDiccionario.isSelected());
            this.diccionarioControlListener.actionPerformed(evt);
        }
    }//GEN-LAST:event_chboxDiccionarioActionPerformed


    private void selectVersion(){

        Bible selected = (Bible)listVersion.getSelectedValue();
        if(selected == null){
            return;
        }
        try{
            Bible b = BibleReader.getBible(selected.getAbreviation().getBible());
            if(getSelectVersionListener()!=null){
                getSelectVersionListener().actionPerformed(new ActionEvent(b, 0, "selectVersion"));
            }
        }catch(Exception e){
            Utils.printToLog("Error al cargar la biblia "+selected, e, Preferences.LOG_LEVEL_ERROR);
        }
        this.setVisible(false);

    }

    @Override
    public void setVisible(boolean aFlag) {
        popup.setVisible(aFlag);
    }



    public ActionListener getSelectVersionListener() {
        return selectVersionListener;
    }

    public void setSelectVersionListener(ActionListener selectVersionListener) {
        this.selectVersionListener = selectVersionListener;
    }


    public void showSelectForegroundColor(){
        if(colorChooser == null){
            colorChooser = new SimpleColorChooser();
        }

        colorChooser.setCurrentColor(Preferences.getInst().getForegroundColor());
        colorChooser.setChoseColorListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    fontColorControlListener.actionPerformed(e);
                }
            });

         javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                colorChooser.showInPopup(labelColorLetra, 0, 0);
            }
        });
         

    }

    public void showSelectBackgrondColor(){
         if(colorChooser == null){
            colorChooser = new SimpleColorChooser();
        }

        colorChooser.setCurrentColor(Preferences.getInst().getBackgrounColor());
        colorChooser.setChoseColorListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    backgroundColorControlListener.actionPerformed(e);
                }
            });
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                colorChooser.showInPopup(labelColorFondo, 0, 0);
            }
        });

    }

    private void setValoresPorDefecto(){
        Preferences.getInst().setValoresPorDefecto();
        setValoresPreferencias();
    }


    private void setValoresPreferencias(){
        this.spinnerSizeLetra.setValue(Preferences.getInst().getFontSize());
        this.chboxMarcadores.setSelected(Preferences.getInst().isReferenciasEnabled());
        this.chboxReferencias.setSelected(Preferences.getInst().isMarcadoresEnables());
        this.chboxDiccionario.setSelected(Preferences.getInst().isDictionaryEnabled());
        
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonValoresPorDefecto;
    private javax.swing.JCheckBox chboxDiccionario;
    private javax.swing.JCheckBox chboxMarcadores;
    private javax.swing.JCheckBox chboxReferencias;
    private wl.ui.ButtonLabel labelColorFondo;
    private wl.ui.ButtonLabel labelColorLetra;
    private javax.swing.JLabel labelTamanoLetra;
    private javax.swing.JList listVersion;
    private javax.swing.JPanel panelOptions;
    private javax.swing.JScrollPane scrollPaneVersion;
    private javax.swing.JSpinner spinnerSizeLetra;
    // End of variables declaration//GEN-END:variables

    public void show(Component inv, int x, int y) {
        setValoresPreferencias();
        popup.show(inv, x, y);
        listVersion.requestFocus();
    }

}
